package com.sky.controller.user;

import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
public class AddressBookController {
  private final AddressBookService addressBookService;
  
  public AddressBookController(AddressBookService addressBookService) {
    this.addressBookService = addressBookService;
  }
  
  /**
   * 保存收货地址信息。
   * @param addressBook
   */
  @PostMapping
  public Result save(@RequestBody AddressBook addressBook) {
    addressBookService.save(addressBook);
    return Result.success();
  }
  
  /**
   * 更新地址簿条目信息。
   * @param addressBook
   */
  @PutMapping
  public Result update(@RequestBody AddressBook addressBook) {
    addressBookService.update(addressBook);
    return Result.success();
  }
  
  /**
   * 获取用户的地址簿列表。
   */
  @GetMapping("/list")
  public Result<List<AddressBook>> list() {
    List<AddressBook> addressBooks = addressBookService.list();
    return Result.success(addressBooks);
  }
  
  /**
   * 获取默认地址簿条目。
   */
  @GetMapping("/default")
  public Result<AddressBook> findDefault() {
    AddressBook addressBook = addressBookService.findDefault();
    return Result.success(addressBook);
  }
  
  /**
   * 设置当前用户的默认地址簿条目。
   */
  @PutMapping("/default")
  public Result setDefault(@RequestBody Map<String, Long> body) {
    System.out.println("body: "+body);
    addressBookService.setDefault(body.get("id"));
    return Result.success();
  }
  
  
  /**
   * 根据ID查找地址簿条目。
   */
  @GetMapping("/{id}")
  public Result<AddressBook> findById(@PathVariable Long id) {
    AddressBook addressBook = addressBookService.findById(id);
    return Result.success(addressBook);
  }
  
  /**
   * 根据ID删除地址簿条目。
   */
  @DeleteMapping
  public Result<?> delById(@RequestParam Long id) {
    addressBookService.delById(id);
    return Result.success();
  }
  
}
